<?php
 if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mcontent extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function Search($keyword,$limit,$stt)
    {
        $data1 =  $this->db->query("SELECT id,title,title_ascii FROM ecoupon WHERE title LIKE '%".$keyword."%' LIMIT $stt,$limit ")->result_object();
        $data2 =  $this->db->query("SELECT id,name,name_ascii FROM restaurant WHERE name LIKE '%".$keyword."%' LIMIT $stt,$limit ")->result_object();
        $data = array( "coupon" => $data1, "restaurant" => $data2 );
        return $data;
    }
    
    public function getNewIncentive($limit,$stt){
        /*$data_fixed =  $this->db->query("SELECT id,title,title_ascii,image,summary,content,type,created FROM incentive_restaurant WHERE type = 0 ORDER BY created DESC LIMIT $stt,$limit ")->result_object();
        $data_monthly =  $this->db->query("SELECT id,title,title_ascii,image,summary,content,type,created FROM incentive_restaurant WHERE type = 1 ORDER BY created DESC LIMIT $stt,$limit ")->result_object();
        //$data = array( "coupon" => $data1, "restaurant" => $data2 );
        $data = array_merge($data_fixed,$data_monthly);*/
	 $data =  $this->db->query("SELECT id,title,title_ascii,image,slide_image AS post_image,summary,content,ecoupon,created FROM incentive_new ORDER BY created DESC LIMIT $stt,$limit ")->result_object();
        return $data;
    }
    
    
    public function getIncentiveFixed($limit,$stt){
        return $this->db->query("SELECT id,title,title_ascii,image,slide_image AS post_image,summary,content,ecoupon,type,created FROM incentive_restaurant WHERE type = 0 ORDER BY created DESC LIMIT $stt,$limit ")->result_object();
    }
    
    public function getIncentiveMonthly($limit,$stt){
        return $this->db->query("SELECT id,title,title_ascii,image,slide_image AS post_image,summary,content,ecoupon,type,created FROM incentive_restaurant WHERE type = 1 ORDER BY created DESC LIMIT $stt,$limit ")->result_object();
    }
    
    public function getRestaurantMenus($id){
        return $this->db->query("SELECT rm.id,rm.zone_id,rm.slide_image,z.title FROM restaurant_menus as rm JOIN zone as z ON rm.zone_id = z.id WHERE rm.restaurant_id = '".$id."' AND rm.active = 1 ORDER BY rm.created DESC ")->result_object();
    }
    
    
    public function getReviewRestaurant($id,$limit,$stt){
        return $this->db->query("SELECT * FROM restaurant_review WHERE restaurant_id = ".$id." AND improved = 1 ORDER BY created DESC LIMIT $stt,$limit ")->result_object();
    }
    
	public function getReviewCoupon($id,$limit,$stt){
		return $this->db->query("SELECT * FROM ecoupon_review WHERE coupon_id = ".$id." AND improved = 1 ORDER BY created DESC LIMIT $stt,$limit ")->result_object();
	}
	
    
    public function submitReviewRestaurant($restaurant_id,$user_id,$name,$star,$content){
        $data = array (
            'restaurant_id' => $restaurant_id,
            'user_id' => $user_id,
            'name' => $name,
            'star' => $star,
            'content' => $content,
            'created' => time(),
            'improved' => 0
            );
            
        $run = $this->db->insert('restaurant_review', $data );
        if($run){
            return 200;
        }else{
            return 201;
        }
    }
    
    
    
     public function submitReviewCoupon($coupon_id,$user_id,$name,$star,$content){
        $data = array (
            'coupon_id' => $coupon_id,
            'user_id' => $user_id,
            'name' => $name,
            'star' => $star,
            'content' => $content,
            'created' => time(),
            'improved' => 0
            );
            
        $run = $this->db->insert('ecoupon_review', $data );
        if($run){
            return 200;
        }else{
            return 201;
        }
    }
    
	public function submitBooking($user_id,$name,$phone,$email,$dates,$time,$restaurant_id,$address_id,$peoples,$is_gpeople,$required){
		$data = array (
				'name' => $name,
				'phone' => $phone,
				'email' => $email,
				'time_booking' => $time.'|'.$dates,
				'address_id' => $address_id,
				'peoples' => $peoples,
				'is_gpeople' => $is_gpeople,
				'required' => $required,
				'improved' => 0,
				'restaurant_id' => $restaurant_id,
				'user_id' => $user_id,
				'created' => time()		
		);
		$run = $this->db->insert('booking', $data);
		//die('999');
		if( $run ){
			$emailAdmin =  $this->getEmailAdmin(); //email admin
			$emailCustomer = $email;
			$data_add = $this->getAddressName($data['address_id']);  // data address
			$this->sendMailAdmin($emailAdmin,$data,$data_add);
			$this->sendMailMember($emailCustomer,$data,$data_add);
			return 200;
		}else{
			return 201;
		}
		
	}
	
	public function sendMailAdmin($emailAdmin,$data,$data_add){
		$config = array(
				'protocol' => 'smtp',
				'smtp_host' => 'mail.gvtechcom.vn',
				'smtp_user' => 'info@gvtechcom.vn',
				'smtp_pass' => 'abcde@123',
				'mailtype' => 'html'
				
			);
		
		foreach ( $emailAdmin AS $item ){
			$this->load->library('email',$config);
			$body    = "<strong>Chào ".$item->fullname ? $item->fullname : 'Bạn'."!</strong> <br /><br /> Có 1 khách hàng vừa đăng kí đặt bàn tại nhà hàng của bạn!<br />Thông tin như sau:<br/>
			Họ tên : ".$data['name']."<br/>
			Số điện thoại : ".$data['phone']."<br/>
			Địa chỉ email :  ".$data['email']."<br/>
			Thời gian đặt bàn : ".$data['time_booking']."<br/>
			Số người : ".$data['peoples']."<br/>
			Địa chỉ nhà hàng : ".$data_add->res_add."<br/>
			Tên nhà hàng : ".$data_add->name_res."<br/>
			";
			$this->email->from('nhatnv@gvtechcom.vn', 'Thông báo đặt bàn');
			$this->email->to((string)$item->email);   // email admin  
			$this->email->subject('Thông báo có khách hàng đặt bàn tại nhà hàng của bạn!');
			$this->email->message($body);    
			$this->email->send();
		}
	}
	
	public function sendMailMember($emailMember,$data,$data_add){
            $config = array(
							'protocol' => 'smtp',
							'smtp_host' => 'mail.gvtechcom.vn',
							'smtp_user' => 'info@gvtechcom.vn',
							'smtp_pass' => 'abcde@123',
							'mailtype' => 'html'
                            
                        );
			$this->load->library('email',$config);
			$body    = "<strong>Chào ".$data['name'] ? $data['name'] : 'Bạn'."!</strong> <br /><br /> Bạn đã đặt bàn tại nhà hàng ".$data_add->name_res." địa chỉ ".$data_add->res_add." !<br />Thông tin như sau:<br/>
			Họ tên : ".$data['name']."<br/>
			Số điện thoại : ".$data['phone']."<br/>
			Địa chỉ email :  ".$data['email']."<br/>
			Thời gian đặt bàn : ".$data['time_booking']."<br/>
			Số người : ".$data['peoples']."<br/>
			Địa chỉ nhà hàng : ".$data_add->res_add."<br/>
			Tên nhà hàng : ".$data_add->name_res."<br/>
			Cảm ơn bạn chúng tôi sẽ liên hệ trong thời gian sớm nhất!";
			$this->email->from('nhatnv@gvtechcom.vn', 'Thông báo đặt bàn');
			$this->email->to((string)$emailMember);   // email admin  
			$this->email->subject('Thông báo có khách hàng đặt bàn tại nhà hàng của bạn!');
			$this->email->message($body);    
			$this->email->send();
	}
	
	public function getEmailAdmin(){   // [{email: "dungdcth@gmail.com",fullname: "mod"},{email: "bocdau@gmail.com",fullname: "Nguyễn Văn Nhất"}];
		return $this->db->query('SELECT u.email as email, u.fullname FROM user as u JOIN permission as p ON u.id = p.id_user WHERE p.id_module = 16 ')->result_object();
	}
	public function getAddressName($address_id){ //{name_res: "Nhà hàng bia hải xồm",res_add: "335 Phố Huê, Hai Bà Tưng"}
		return $this->db->query('SELECT r.name as name_res, ra.address as res_add FROM restaurant as r JOIN restaurant_address as ra ON r.id = ra.restaurant_id WHERE ra.id = '.$address_id)->row_object();
	}
	
    
    public function loginUser()
    {
        
    }
    
    
    public function registerUser($username)
    {
        $pass = $this->generateCode(6);
        $pass_encode = md5(md5($username).md5($pass));
        $qr = $this->db->query('SELECT * FROM user WHERE username = "'.strtolower($username).'"');
        $check = $qr->num_rows();
        
        if($check == 0)
        {
            $data = array(
                'username'  => $username,
                'password'  => $pass_encode
            );  
            $this->db->insert('user', $data);
	        $ID = $this->db->insert_id();
            $this->sendOTP($username, $pass);
            
            $_data = $this->db->query('SELECT * FROM user WHERE id = '.$ID)->row_object();
            $_data->password = null;
            return (object)array('status' => 200, 'content' => $_data);
        }else{
            $data = array(
                'password'  => $pass_encode
            );  
            $this->db->update('user', $data, "username = '".strtolower($username)."'");
            $this->sendOTP($username, $pass);
            $_data = $this->db->query('SELECT * FROM user WHERE username = "'.strtolower($username).'"')->row_object();
            $_data->password = null;
            return (object)array('status' => 200, 'content' => $_data);
        }   
    }
    
    public function getDataUser($id)
    {
        return $this->db->query('SELECT * FROM user WHERE id = '.$id)->row_object();
    }
    
    public function infoUser($id)
    {
        return $this->db->query('SELECT * FROM user WHERE id = '.$id)->row_object();
    }
    
    
    private function exNumberPhone($num)
    {
        return '84'.substr($num, 1);
    }
    
    private function sendOTP($dest, $otp, $types = 0)
    {
        if($types == 1)
        {
            $body = "VTV New Password:\n Mat khau moi cua ban la: ".$otp;
        }else{
            $body = "VTV OTP Code:\n Ma xac thuc cua ban la: ".$otp;
        }
        $NumberPhone = $this->exNumberPhone($dest);
    	$moid = '0';
    	$moseq = '0';
    	$src = '8069';
    	$cmdcode = '';
    	$msgtype = 'Text';
    	$msgtitle = '';
    	$mttotalseg = '1';
    	$mtseqref = '1';
    	$procresult ='1';
	$cpid = '10424';
    	$username = '3';
    	$password = 'e#@$';
    	$WSDL = "http://agent.gapit.com.vn/AgentWS_SureM/SMSAgentWS.asmx?wsdl";
    	$client = new SoapClient($WSDL);
    	$mtseq = date('YmdHis').rand(0,999);
    
    	$data = array(
    		'mtseq'         =>    $mtseq,
    		'moid'          =>    $moid,
    		'moseq'         =>    $moseq,
    		'src'           =>    $src,
    		'dest'          =>    $NumberPhone,
    		'cmdcode'       =>    $cmdcode,
    		'msgbody'       =>    $body,
    		'msgtype'       =>    $msgtype,
    		'msgtitle'      =>    $msgtitle,
    		'mttotalseg'    =>    $mttotalseg,
    		'mtseqref'      =>    $mtseqref,
    		'cpid'          =>    $cpid,
    		'reqtime'       =>    date("d/m/Y h:i:s A"),
    		'serviceid'     =>    'Service01',
    		'procresult'    =>    $procresult,        
    		'username'      =>    $username,
    		'password'      =>    $password
    	);
    
    	$status = $client->SendMT($data);         
    }
    
    
    public function changePassDB()
    {
        $uname = $this->getParamString('username');
        $upassold = $this->getParamString('passwordold');
        $upassnew = $this->getParamString('passwordnew');
        $passwordcfr = $this->getParamString('passwordcfr');

        $pass_encode = md5(md5($uname).md5($upassold));
        
        $sql = $this->db->query("SELECT * FROM user WHERE username = '".strtolower($uname)."' AND password = '".$pass_encode."' ");
        if($sql->num_rows() > 0)
        {
            if($upassnew != $passwordcfr)
            {
                return 201;
            }
    
            $pass_en_code = md5(md5($uname).md5($upassnew));
            $data = array(
                'password'  => $pass_en_code
            );  
            $this->db->update('user', $data, "username = '".strtolower($uname)."'");
            return 200;
        }else{
            return 404;
        }

    }
    
    
    public function forGotDB()
    {
        $pass = $this->generateCode(6);
        $uname = $this->getParamString('username');
        $pass_encode = md5(md5($uname).md5($pass));
        
        $qr = $this->db->query('SELECT * FROM user WHERE username = "'.strtolower($uname).'"');
        $check = $qr->num_rows();
        
        if($check > 0)
        {
            $data = array(
                'password'  => $pass_encode
            );  
            $this->db->update('user', $data, "username = '".strtolower($uname)."'");
            $this->sendOTP($uname, $pass, 1);
            return 200;
        }else{
            return 404;
        }
    }
    
    
    public function followDB()
    {
        $id_user = $this->getParamInt('user_id');
        $id_tvshow = $this->getParamInt('id_tvshow');
        $sql = $this->db->query('SELECT id FROM follow_tvshow WHERE user_id = '.$id_user.' AND tvshow_id = '.$id_tvshow);
        
        $check = $sql->num_rows();
        if($check > 0)
        {
            $id = $sql->row_object()->id;
            $this->db->delete('follow_tvshow', "id = ".$id);
            return (object)array('status' => 201, 'Hủy thành công');
        }else{
            $this->db->insert('follow_tvshow', array('user_id' => $id_user, 'tvshow_id' => $id_tvshow, 'created' => time()));
            return (object)array('status' => 200, 'Thêm thành công');
        }
        return (object)array('status' => 202, 'Lỗi khác');
    }
    
	
    public function getIncentiveLabel($limit,$stt,$label){
        $data =  $this->db->query("SELECT ir.id,ir.title,ir.title_ascii,ir.image,ir.summary,ir.content,ir.type,ir.created FROM incentive_restaurant AS ir LEFT JOIN incentive_restaurant_key AS irk ON irk.id_incentive = ir.id LEFT JOIN restaurant AS r ON r.id = irk.id_restaurant WHERE irk.id_restaurant = $label OR ir.type_sl = 0 ORDER BY created DESC LIMIT $stt,$limit ")->result_object();
        return $data;
    }
}
